<template>
  <div>
    <el-form
      :model="friendForm"
      :rules="rules"
      ref="FriendForm"
      label-width="80px">
      <el-form-item
        label="选择分组"
        prop="organizationId">
        <el-select v-model="friendForm.organizationId" placeholder="请选择分组">
          <el-option
            v-for="organization in organizationInfo"
            :key="organization.organizationId"
            :label="organization.organizationName"
            :value="organization.organizationId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button @click="cancelSubmit">
        取消
      </el-button>
      <el-button type="primary" @click="submitForm('FriendForm')">
        确定
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AddFriendForm',
  props: {
    msgKey: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      friendForm: {
        key: '',
        organizationId: ''
      },
      rules: {
        organizationId: [
          { required: true, message: '请输入群组名', trigger: 'blur' }
        ]
      },
      organizationInfo: []
    }
  },
  computed: {

  },
  watch: {
    msgKey (newVal) {
      this.friendForm.key = newVal
    }
  },
  mounted () {
    this.friendForm.key = this.msgKey
    this.handleOrganizationInfo()
  },
  methods: {
    // 获取分组信息
    handleOrganizationInfo () {
      this.$request.contact.organizationInfo(
        res => {
          this.organizationInfo = res.data
          if (this.organizationInfo.length > 0) {
            this.friendForm.organizationId = this.organizationInfo[0].organizationId
          }
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 提交修改表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleAddFriend()
        } else {
          return false
        }
      })
    },
    /**
     * 添加好友
     */
    handleAddFriend () {
      this.$request.contact.addFriend(
        this.friendForm.key,
        this.friendForm.organizationId,
        res => {
          this.$message.success('添加成功')
          this.$emit('submit')
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    }
  }
}
</script>
